package com.shanzmoo.db.personnel.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shanzmoo.db.personnel.entity.MemberInvoiceEntity;
import com.shanzmoo.db.personnel.entity.dto.MemberInvoiceSaveDto;
import com.shanzmoo.db.personnel.entity.vo.MemberInvoiceVo;
import com.shanzmoo.db.personnel.mapper.MemberInvoiceMapper;
import com.shanzmoo.db.personnel.service.IMemberInvoiceService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 会员发票 服务实现类
 * </p>
 *
 * @author Gzhao
 * @since 2020-12-25
 */
@Service
public class MemberInvoiceServiceImpl extends ServiceImpl<MemberInvoiceMapper, MemberInvoiceEntity> implements IMemberInvoiceService {

    @Override
    public void addInvoice(String memberId, MemberInvoiceSaveDto saveDto) {
        MemberInvoiceEntity invoiceEntity = saveDto.convert();
        invoiceEntity.setMemberId(Integer.parseInt(memberId));
        invoiceEntity.setDefaultInvoice(true);

        List<MemberInvoiceEntity> list = baseMapper.selectList(
                new QueryWrapper<MemberInvoiceEntity>()
                        .eq("deleted", false)
                        .eq("member_id", memberId)
        );
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(e->{
                e.setDefaultInvoice(false);
            });
            this.updateBatchById(list);
        }
        baseMapper.insert(invoiceEntity);
    }

    @Override
    public MemberInvoiceVo obtianInvoice(String memberId) {
        MemberInvoiceEntity invoiceEntity = baseMapper.selectOne(
                new QueryWrapper<MemberInvoiceEntity>()
                        .eq("deleted", false)
                        .eq("member_id", memberId)
                        .eq("default_invoice", true)
        );
        return MemberInvoiceVo.create(invoiceEntity);
    }
}
